package net.hn.hnms.sys.system.cron;

import cn.dev33.satoken.secure.BCrypt;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.sys.common.core.utils.DateUtils;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.core.utils.tool.Func;
import net.hn.hnms.sys.system.api.domain.SysUser;
import net.hn.hnms.sys.system.service.ISysDeptService;
import net.hn.hnms.sys.system.service.ISysUserService;
import net.hn.hnms.sys.system.service.IhnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * i 华能 用户更新 定时任务
 */
@Component
@Slf4j
@Async
//加上该注解不执行定时任务
//@ComponentScanIgnore
//@RefreshScope注解实现动态刷新原理
//@RefreshScope
public class IhnUserCron {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    IhnService ihnService;
//    @Autowired
//    IIhnInterfaceDataService ihnInterfaceDataService;
    /**
     * 每10秒读取煤流数据，写入大屏报警表中
     */
//     @Scheduled(cron = "0/30 * * * * ?")//每30秒执行一次
//    @Scheduled(cron = "0 0/2 * * * ?")//每分钟执行一次
//    @Scheduled(cron = "0 10 12 * * ?")//每天12:10点执行
    @Scheduled(cron = "0 52 01 * * ?")//每天01:52分执行
//    @Async("rhdScheduleExecutor")
//   @OneTimeSchedule(lockName = "PushAndMessageCron.pushData", timeout = 600L)
//    @Async("ddtsScheduleExecutorConfig") //异步定时任务
    public void pushData() {
        try {
            log.error("i华能数据同步开始");
            Date currentDate = new Date();
            String deptId="6771";//西川煤矿，264是煤业数据
            ihnUser_update(deptId, new Date());


//            List<String> list = ihnInterfaceDataService.usersByDeptId(Long.valueOf(deptId), true);
//            //跟新用户详情信息
//            ihnInterfaceDataService.userListDetails(list);

            log.error("i华能数据同步结束");
        }catch (Exception e){
            e.printStackTrace();
            log.error("i华能数据失败");
        }

    }

    /**
     * i华能 对应部门下用户数据更新
     * @param department_id 部门ID，
     */
    private void ihnUser_update(String department_id, Date parse) {

//        log.debug("部门数据更新同步开始时间："+DateUtil.format(DateUtil.plusSeconds(parse, 0),DateUtil.PATTERN_TIME));
        log.debug("部门数据更新同步开始时间："+ DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,parse));

        String data = ihnService.userSimplelist(department_id,"1");
        boolean b=false;
        if (StringUtils.isNotEmpty(data)){
            System.out.println(data);
            JSONObject jsonObject = JSONObject.parseObject(data);
            int errcode = jsonObject.getIntValue("code");
            if (errcode == 200){
                JSONArray department = jsonObject.getJSONArray("body");
                List<SysUser> ihnUserInfos = new ArrayList<>(department.size());
                for (int i = 0; i < department.size(); i++) {
                    JSONObject o =(JSONObject) department.get(i);
                    SysUser javaObject = o.toJavaObject(SysUser.class);
                    if (o.getString("department").contains(",")){
                        String[] departments = o.getString("department").split(",");
//                        javaObject.setDeptId(Long.valueOf(departments[0]));
                        javaObject.setDeptId(o.getString("department"));
                    }else{
//                        javaObject.setDeptId(Long.valueOf(o.getString("department")));
                        javaObject.setDeptId(o.getString("department"));
                    }
                    javaObject.setNickName(o.getString("name"));
                    javaObject.setUserName(javaObject.getUserId()+"");
                    javaObject.setPhonenumber(o.getString("mobile"));
                    if (StringUtils.isNotEmpty(javaObject.getPhonenumber())){
                        System.out.println((javaObject.getPhonenumber()+""));
                        javaObject.setPassword(BCrypt.hashpw(javaObject.getPhonenumber().trim()));
                    }
//                    try {
//                        javaObject.setId(Long.valueOf(javaObject.getUserid()));
//                    }catch (Exception e){
//                        System.out.println(javaObject.getUserid());
//                        LambdaQueryWrapper<IhnUserInfo> queryWrapper = Wrappers.lambdaQuery();
//                        queryWrapper.eq(IhnUserInfo::getUserid, javaObject.getUserid());
//                        IhnUserInfo one = ihnUserInfoService.getOne(queryWrapper);
//                        if (Func.isNotEmpty(one)) {
//                            javaObject.setId(one.getId());
//                        }
//
//                    }
//                    javaObject.setUpdateTime(new Date());
//                    if (ObjectUtils.isEmpty(javaObject.getCreateTime())) {
//                        javaObject.setCreateTime(new Date());
//                    }

//                    if(i==0){
//                        ihnUserInfos.add(javaObject);
//                    }
                    SysUser byId = sysUserService.getById(javaObject.getUserId());
                    if (Func.isNotEmpty(byId)){

                    }else{
                        //只更新新增的数据
                        ihnUserInfos.add(javaObject);
                    }

                }
                if (Func.isNotEmpty(ihnUserInfos)){
                    b = sysUserService.saveOrUpdateBatch(ihnUserInfos);
                }

            }

//            return Response.success(b);
        }else{
//            return Response.success(b);
        }
//        log.debug("部门数据更新同步结束时间："+DateUtil.format(DateUtil.plusSeconds(parse,0),DateUtil.PATTERN_TIME));
        log.debug("部门数据更新同步结束时间："+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date()));


    }




}
